/*
 * 文件名：ProtocalSdtpDataDecode.java
 * 版权：亚信联创版权所有
 * 描述：TODO
 * 修改人：xuwei3
 * 修改时间：2015-5-20
 * 修改内容：TODO
 */
package com.ailk.bigdata.etl.realstream.server.protocal.sdtp.netty.handler;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ailk.bigdata.etl.common.server.net.NettyUtil;
import com.ailk.bigdata.etl.realstream.server.constant.ProtocalSdtpConstant;
import com.ailk.bigdata.etl.realstream.server.model.Header;
import com.ailk.bigdata.etl.realstream.server.model.MessageType;
import com.ailk.bigdata.etl.realstream.server.model.SdtpDataPack;
import com.google.common.primitives.UnsignedInteger;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

/**
 * @description TODO
 * @author [xuwei3]
 * @version [版本号,2015-5-20]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class ProtocalSdtpDataDecode extends ReplayingDecoder<SdtpDataPack>
{
	private static Logger logger = LoggerFactory.getLogger(ProtocalSdtpDataDecode.class);

	/**
	 * @see io.netty.handler.codec.ByteToMessageDecoder#decode(io.netty.channel.ChannelHandlerContext,
	 *      io.netty.buffer.ByteBuf, java.util.List)
	 */
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> message) throws Exception
	{
		// 解包
		byteBuf.markReaderIndex();

		int totalLength = byteBuf.readUnsignedShort() - 9;// 2
		int messageType = byteBuf.readUnsignedShort();// 2
		UnsignedInteger sequenceId = UnsignedInteger.valueOf(byteBuf.readUnsignedInt());// 4
		short totalContents = byteBuf.readUnsignedByte();// 1

		Header header = new Header();
		header.setTotalLength(totalLength);
		header.setMessageType(messageType);
		header.setSequenceId(sequenceId);
		header.setTotalContents(totalContents);

		SdtpDataPack pack = new SdtpDataPack();

		if (messageType == MessageType.notifyCDRData_Req.getValue())
		{
			totalLength -= 10;

			int cdrType = byteBuf.readUnsignedShort();
			int dataType = ProtocalSdtpConstant.SDTP_DATA_TYPE_BASE * messageType + cdrType;
			pack.setDataType(dataType);
			pack.setCdrId(byteBuf.readLong());
		}
		else if (messageType == MessageType.XDRRawDataSend_Req.getValue())
		{
			totalLength -= 8;
			pack.setDataType(ProtocalSdtpConstant.SDTP_DATA_TYPE_BASE * messageType);
			pack.setCdrId(byteBuf.readLong());
		}

		ByteBuf dataContent = byteBuf.readBytes(totalLength);

		pack.setHeader(header);
		pack.setDataContent(dataContent);

		message.add(pack);

		if (logger.isDebugEnabled())
		{
			logger.debug("服务端接收到一条来自客户端[{}]的消息,消息类型是[{}],包长[{}]", NettyUtil.getClientAdd(ctx), messageType, totalLength);
		}
	}
}
